import { EngineTemplate, EngineComponent } from './../../../models';
import { Component, OnInit, Input, ViewChildren, QueryList, ViewContainerRef, AfterViewInit } from '@angular/core';
import { ComponentMapTool } from '../../../tools/component-map-tool';
import { RenderComponentConfig } from '../../../models/render-component-config';
import { BaseContainerComponent } from '../base-container.component';
import { v4 as UUID } from 'uuid';

@Component({
  selector: 'zepride-template-container',
  templateUrl: './template-container.component.html',
  styleUrls: ['./template-container.component.less']
})
export class TemplateContainerComponent extends BaseContainerComponent implements OnInit, AfterViewInit {

  @ViewChildren('componentViewContainerRef', { read: ViewContainerRef }) componentViewContainerRef: QueryList<ViewContainerRef>;
  private _flowNodeTemplate: EngineTemplate;

  @Input() set data(templateData: EngineTemplate) {
    this._flowNodeTemplate = templateData;
  }

  get flowNodeTemplate() {
    return this._flowNodeTemplate;
  }

  ngOnInit(): void { }

  ngAfterViewInit() {
    const components = this.flowNodeTemplate.components;
    this.renderComponents(components);
  }

  renderComponents(components: EngineComponent[]) {
    const refs = this.componentViewContainerRef.toArray();
    components.forEach((component, index) => {
      const config = this.generateRenderConfig(component, refs[index]);
      if (config) {
        this.engineService.renderComponent(config);
      }
    });
  }

  generateRenderConfig(component: EngineComponent, viewContainerRef: ViewContainerRef) {
    const uuid = UUID().replace(/-/g, '');
    component.identifyId = uuid;
    const renderItem = ComponentMapTool.current.getRenderItem(component.selector, component);
    if (renderItem) {
      const config: RenderComponentConfig = {
        renderItem,
        viewContainerRef
      };
      return config;
    } else {
      return null;
    }
  }
}
